<template>
  <div class="map-wrapper">
    <div class="search-box" v-if="editable">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索地点"
        size="small"
        @keyup.enter.native="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
    </div>
    <div class="map-container" ref="mapContainer"></div>
  </div>
</template>

<script>
export default {
  name: 'AMap',
  props: {
    // 经度
    longitude: {
      type: [Number, String],
      default: 116.404
    },
    // 纬度
    latitude: {
      type: [Number, String],
      default: 39.915
    },
    // 缩放级别
    zoom: {
      type: Number,
      default: 15
    },
    // 是否允许编辑（拖动标记点）
    editable: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      map: null,
      marker: null,
      AMap: null,
      searchKeyword: '',
      placeSearch: null,
      geocoder: null
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    initMap() {
      // 确保高德地图脚本已加载
      if (typeof AMap === 'undefined') {
        // 设置安全密钥
        window._AMapSecurityConfig = {
          securityJsCode: process.env.VUE_APP_AMAP_SECURITY_CODE
        }
        
        const script = document.createElement('script')
        script.src = `https://webapi.amap.com/maps?v=2.0&key=${process.env.VUE_APP_AMAP_KEY}&callback=initAMap`
        document.body.appendChild(script)
        window.initAMap = () => {
          this.initMapInstance()
        }
      } else {
        this.initMapInstance()
      }
    },
    initMapInstance() {
      this.AMap = AMap
      this.map = new AMap.Map(this.$refs.mapContainer, {
        zoom: this.zoom,
        center: [this.longitude, this.latitude],
        viewMode: '3D'
      })

      // 加载地图控件插件
      AMap.plugin([
        'AMap.Scale',
        'AMap.ToolBar',
        'AMap.PlaceSearch',
        'AMap.Geocoder',
        'AMap.AutoComplete'
      ], () => {
        // 添加地图控件
        this.map.addControl(new AMap.Scale())
        this.map.addControl(new AMap.ToolBar())

        if (this.editable) {
          // 初始化搜索服务
          this.placeSearch = new AMap.PlaceSearch({
            city: '全国',
            pageSize: 1,
            pageIndex: 1,
            extensions: 'all'
          })

          // 初始化地理编码服务
          this.geocoder = new AMap.Geocoder()
        }
      })
      // 添加标记点
      this.marker = new AMap.Marker({
        position: [this.longitude, this.latitude],
        draggable: this.editable,
        icon: new AMap.Icon({
          size: new AMap.Size(25, 34),
          image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
          imageSize: new AMap.Size(25, 34)
        })
      })
      this.map.add(this.marker)

      if (this.editable) {
        // 标记点拖动结束事件
        this.marker.on('dragend', (e) => {
          const position = this.marker.getPosition()
          this.$emit('marker-move', {
            longitude: position.getLng(),
            latitude: position.getLat()
          })
        })
      }

      // 点击地图更新标记点位置
      this.map.on('click', (e) => {
        if (this.editable) {
          const position = e.lnglat
          console.log('地图点击位置:', position.getLng(), position.getLat());
          this.marker.setPosition([position.getLng(), position.getLat()])
          this.$emit('marker-move', {
            longitude: position.getLng(),
            latitude: position.getLat()
          })
        }
      })
    },
    handleSearch() {
      if (this.searchKeyword && this.placeSearch) {
        this.placeSearch.search(this.searchKeyword, (status, result) => {
          if (status === 'complete') {
            if (result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
              const firstPoi = result.poiList.pois[0]
              const position = [firstPoi.location.lng, firstPoi.location.lat]
              this.marker.setPosition(position)
              this.map.setCenter(position)
              this.$emit('marker-move', {
                longitude: firstPoi.location.lng,
                latitude: firstPoi.location.lat
              })
              // 显示成功提示
              this.$message.success('已定位到: ' + firstPoi.name)
            } else {
              this.$message.warning('未找到相关地点')
            }
          } else {
            this.$message.error('搜索失败，请重试')
          }
        })
      } else {
        this.$message.warning('请输入搜索关键词')
      }
    },
    // 地理编码：地址转换为经纬度
    geocodeAddress(address) {
      return new Promise((resolve, reject) => {
        if (!address || !this.geocoder) {
          reject(new Error('地理编码服务未初始化'));
          return;
        }

        this.geocoder.getLocation(address, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            const location = result.geocodes[0].location;
            const position = [location.lng, location.lat];
            this.marker.setPosition(position);
            this.map.setCenter(position);
            resolve({
              location: {
                lng: location.lng,
                lat: location.lat
              }
            });
          } else {
            reject(new Error('地理编码失败'));
          }
        });
      });
    },

    // 逆地理编码：经纬度转换为地址
    reverseGeocode(longitude, latitude) {
      console.log('开始逆地理编码:', longitude, latitude);
      return new Promise((resolve, reject) => {
        if (!this.geocoder) {
          console.error('逆地理编码服务未初始化');
          reject(new Error('逆地理编码服务未初始化'));
          return;
        }

        this.geocoder.getAddress([longitude, latitude], (status, result) => {
          console.log('逆地理编码结果:', status, result);
          if (status === 'complete' && result.info === 'OK') {
            const addressComponent = result.regeocode.addressComponent;
            const response = {
              address: result.regeocode.formattedAddress,
              addressComponent: {
                province: addressComponent.province,
                city: addressComponent.city,
                district: addressComponent.district,
                street: addressComponent.street,
                streetNumber: addressComponent.streetNumber
              }
            };
            console.log('处理后的地址信息:', response);
            resolve(response);
          } else {
            console.error('逆地理编码失败:', status, result);
            reject(new Error('逆地理编码失败'));
          }
        });
      });
    }
  },
  watch: {
    longitude(newVal) {
      if (this.marker) {
        const position = this.marker.getPosition()
        this.marker.setPosition([newVal, position.getLat()])
        this.map.setCenter([newVal, position.getLat()])
      }
    },
    latitude(newVal) {
      if (this.marker) {
        const position = this.marker.getPosition()
        this.marker.setPosition([position.getLng(), newVal])
        this.map.setCenter([position.getLng(), newVal])
      }
    }
  }
}
</script>

<style scoped>
.map-wrapper {
  width: 100%;
  height: 100%;
  min-height: 400px;
  position: relative;
  background-color: #f5f5f5;
}

.map-container {
  width: 100%;
  height: 100%;
  min-height: 400px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.search-box {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 300px;
  z-index: 9999;
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  pointer-events: auto;
}

.search-box :deep(.el-input__inner) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.search-box :deep(.el-input-group__append) {
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
  color: white;
  padding: 0 15px;
}

.search-box :deep(.el-input-group__append:hover) {
  background-color: var(--el-color-primary-light-3);
  border-color: var(--el-color-primary-light-3);
}

/* 隐藏高德地图Logo和版权信息 */
:deep(.amap-logo) {
  display: none !important;
}

:deep(.amap-copyright) {
  display: none !important;
}
</style> 